Imports System.IO
Imports System.Net
Imports System.Threading
Imports System.Xml




Public Module QfinitiExport
    
    Private ar(5) As String
    Private verStatus As String
    Private transID As String
    Private statusFTP As String
    Private BorrarDataFile As Boolean
    Private FlagDel As Integer
    Private dirExport As String
    Private dirLog As String
    Private URI As String
    Private UserFTP As String
    Private PassFTP As String
    Private n As Integer
    Private Timer As Integer
    Private FTPTimeOut As Integer
    Private xportDataFile As Boolean
    Private dirInstall As String
    Private DSource As Integer
    Private Rext As String 'Ruta de la app externa para adaptacion de la data a exportar
    Private loglen As Long

    Private xmlCuenta As Integer
    Private xmlDataSource As New XmlDocument
    Private xmlDSNodos As XmlNodeList
    Private xmlDSNodo As XmlNode

    Private usngProxy As Boolean




    Public Sub Main()


        inicializar()

        log("Rutina:Main")
        archivo()

start:  Try

            DS()

            For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirExport, FileIO.SearchOption.SearchTopLevelOnly, "Data.xml")
                XML(foundFile)
            Next


            Threading.Thread.Sleep(Timer)


            GoTo start

        Catch ex As Exception
            log(ex.Message)

            Exit Sub
        End Try

    End Sub


    Sub inicializar()

        Try

            Dim xmldoc As New XmlDocument()
            Dim a As String
            Dim b As Integer


            Try
                dirInstall = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Anew\AppQfinitiExport", "dirInstall", Nothing).ToString.Trim
            Catch ex As Exception
                dirInstall = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Wow6432Node\Anew\AppQfinitiExport", "dirInstall", Nothing).ToString.Trim
            End Try


            xmldoc.Load(dirInstall & "ConfigAppExport.xml")



            Timer = xmldoc.SelectSingleNode("/CONFIG/TIMER").InnerXml

            UserFTP = xmldoc.SelectSingleNode("/CONFIG/FTPINFO/USER").InnerXml
            PassFTP = xmldoc.SelectSingleNode("/CONFIG/FTPINFO/PASS").InnerXml
            URI = xmldoc.SelectSingleNode("/CONFIG/FTPINFO/URI").InnerXml
            FTPTimeOut = xmldoc.SelectSingleNode("/CONFIG/FTPINFO/TIMEOUT").InnerXml

            DSource = xmldoc.SelectSingleNode("/CONFIG/DS/DSOURCE").InnerXml
            Rext = xmldoc.SelectSingleNode("/CONFIG/DS/REXT").InnerXml

            loglen = System.Convert.ToInt64(xmldoc.SelectSingleNode("/CONFIG/INFOLOG/LOGLEN").InnerXml) * 1000
            a = xmldoc.SelectSingleNode("/CONFIG/INFOLOG/DIRLOG").InnerXml
            b = a.Length
            If a = "" Then
                dirLog = dirInstall
            Else
                If InStr(b - 1, a, "\") = 0 Then
                    dirLog = a.Insert(b, "\")
                Else
                    dirLog = a
                End If
            End If

            dirExport = dirInstall & "FTP\"

        Catch ex As Exception

            dirExport = "C:\ToExport\"
            dirLog = dirInstall & "Logs"
            URI = "ftp://"
            UserFTP = "QFDOMCLOUD\BanescoFTP"
            PassFTP = "b@nesc0FTPqf1n1t1"
            Timer = 3600000 'en milisegundos
            FTPTimeOut = 1000 ' en milisegundos
            log(ex.Message)

        End Try


    End Sub


    Sub XML(ByVal archXML As String)
        log("Rutina:XML")

        archivo()
        If ping() = True Then

            Dim fileWAV As String = ""

            Dim x As String = ""
            Dim c As String = ""

            n = 0
            BorrarDataFile = True
            xportDataFile = False

            Try
                log("Leyendo archivo XML: " & archXML)
                xmlDataSource.Load(archXML)
                xmlDSNodos = xmlDataSource.GetElementsByTagName("transaction")
                xmlCuenta = xmlDSNodos.Count

                Do While n < xmlCuenta
                    xmlDSNodo = xmlDSNodos.ItemOf(n)

                    transID = xmlDSNodo.Attributes("trans_id").Value
                    verStatus = Verificar(transID)

                    If verStatus = "0" Then
                        FlagDel = 1
                        fileWAV = xmlDSNodo.Attributes("namefile").Value
                        Control(fileWAV, n, transID, True, True, archXML)
                        n = n + FlagDel

                    ElseIf verStatus = "1" Or verStatus = "2" Then
                        FlagDel = 1
                        fileWAV = xmlDSNodo.Attributes("namefile").Value
                        Control(fileWAV, n, transID, False, True, archXML)
                        n = n + FlagDel

                    ElseIf verStatus = "Error" Then
                        Exit Sub

                    ElseIf xportDataFile = True Then
                        enviarXML(verStatus, False)
                        xmlDSNodo.ParentNode.RemoveChild(xmlDSNodo)
                        xmlCuenta = xmlDSNodos.Count
                        xmlDataSource.Save(archXML)
                        Borrar(xmlDSNodo.Attributes("namefile").Value)

                    Else

                        xmlDSNodo.ParentNode.RemoveChild(xmlDSNodo)
                        xmlCuenta = xmlDSNodos.Count
                        xmlDataSource.Save(archXML)
                        Borrar(xmlDSNodo.Attributes("namefile").Value)

                    End If
                Loop

                xmlDataSource.Save(archXML)


                If BorrarDataFile = True Then
                    Borrar(archXML.Replace(dirExport, ""))
                End If




            Catch ex As Exception

                log(ex.Message)
                Exit Sub

            End Try
        Else
            log("Servidor inaccesible...")
        End If

    End Sub

    Sub enviarXML(ByVal name As String, ByVal op As Boolean)
        log("Rutina:enviarXML")

        ftp(name)
        ar(0) = "#xml#"
        ar(1) = name
        ar(2) = statusFTP
        ar(3) = "Existe"
        ar(4) = dirExport
        ar(5) = FechayHora()

        If op = True Then
            XMLModif(ar)
        Else
            XMLmodif2(ar)
        End If

        log("Archivo XML: " & statusFTP)

        If statusFTP = "Exportado" Then
            Borrar(name)
        End If

    End Sub

    Sub archivo()
        log("Rutina:archivo")


        Dim result As String = ""
        Try
            For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirInstall, FileIO.SearchOption.SearchTopLevelOnly, "dbcontrol.xml")
                result = foundFile
            Next

            If result = "" Then
                Dim xmlFile As New XmlTextWriter(dirInstall & "dbcontrol.xml", System.Text.Encoding.UTF8)
                With xmlFile
                    .WriteStartDocument()
                    .WriteStartElement("Events", "http://www.anew.com.ve/qfiniti")
                    .WriteEndElement()
                    .WriteEndDocument()
                    .Close()

                End With

            End If

        Catch ex As Exception
            log(ex.Message)
        End Try

    End Sub

    Sub XMLModif(ByVal ar As Array)
        log("Rutina:XMLModif")

        Dim xmldoc As New XmlDocument()
        Dim xmlnodes As XmlNodeList
        Dim xmlnode As XmlNode
        Dim xmlelem As XmlElement

        Try
            log("Actualizando archivo dbcontrol.xml")

            xmldoc.Load(dirInstall & "dbcontrol.xml")

            xmlnodes = xmldoc.GetElementsByTagName("Events")

            For Each xmlnode In xmlnodes
                xmlelem = xmldoc.CreateElement("transaction")
                xmlnode.PrependChild(xmlelem)
                With xmlelem
                    .SetAttribute("trans_id", ar(0))
                    .SetAttribute("name_file", ar(1))
                    .SetAttribute("status_ftp", ar(2))
                    .SetAttribute("status_file", ar(3))
                    .SetAttribute("file_path", ar(4))
                    .SetAttribute("date", ar(5))
                End With

            Next
            xmldoc.Save(dirInstall & "dbcontrol.xml")
        Catch ex As Exception
            log(ex.Message)
        End Try

    End Sub

    Sub XMLmodif2(ByVal ar As Array)
        log("Rutina:XMLModif2")


        Dim document As XmlDocument = New XmlDocument()
        Dim navigator As XPath.XPathNavigator = document.CreateNavigator()
        Dim manager As XmlNamespaceManager = New XmlNamespaceManager(navigator.NameTable)

        Try
            log("Actualizando archivo dbcontrol.xml")

            document.Load(dirInstall & "dbcontrol.xml")
            manager.AddNamespace("lg", "http://www.anew.com.ve/qfiniti")

            If ar(0) = "#xml#" Then
                navigator.SelectSingleNode("/lg:Events/transaction[@name_file = '" & ar(1) & "' and @status_ftp = 'No Exportado']/@status_file", manager).SetValue(ar(3))
                navigator.SelectSingleNode("/lg:Events/transaction[@name_file = '" & ar(1) & "' and @status_ftp = 'No Exportado']/@file_path", manager).SetValue(ar(4))
                navigator.SelectSingleNode("/lg:Events/transaction[@name_file = '" & ar(1) & "' and @status_ftp = 'No Exportado']/@date", manager).SetValue(ar(5))
                navigator.SelectSingleNode("/lg:Events/transaction[@name_file = '" & ar(1) & "' and @status_ftp = 'No Exportado']/@status_ftp", manager).SetValue(ar(2))
            Else
                navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & ar(0) & "']/@status_file", manager).SetValue(ar(3))
                navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & ar(0) & "']/@status_ftp", manager).SetValue(ar(2))
                navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & ar(0) & "']/@name_file", manager).SetValue(ar(1))
                navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & ar(0) & "']/@file_path", manager).SetValue(ar(4))
                navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & ar(0) & "']/@date", manager).SetValue(ar(5))
            End If


            document.Save(dirInstall & "dbcontrol.xml")
        Catch ex As Exception
            log(ex.Message)
        End Try

    End Sub

    Sub Control(ByVal name As String, ByVal fila As Integer, ByVal TID As String, ByVal op As Boolean, ByVal op2 As Boolean, ByVal archXML As String)
        log("Rutina:Control")

        If name = "" Then

            BorrarDataFile = False
            ar(0) = TID
            ar(1) = ""
            ar(2) = "No Exportado"
            ar(3) = "No Existe"
            ar(4) = ""
            ar(5) = FechayHora()


            If op = True Then
                XMLModif(ar)
            Else
                XMLmodif2(ar)
            End If

        ElseIf XMLwrite(name) = True Then

            ftp(name)
            ar(0) = TID
            ar(1) = name
            ar(2) = statusFTP
            ar(3) = "Existe"
            ar(4) = dirExport
            ar(5) = FechayHora()

            If op = True Then
                XMLModif(ar)
            Else
                XMLmodif2(ar)
            End If

            If statusFTP = "Exportado" Then
                enviarXML(name.Replace(".wav", ".xml"), op2)
                Borrar(name)

                xmlDSNodo.ParentNode.RemoveChild(xmlDSNodo)
                xmlCuenta = xmlDSNodos.Count
                xmlDataSource.Save(archXML)
                FlagDel = 0
            Else
                BorrarDataFile = False
            End If

        End If


    End Sub

    Sub ftp(ByVal archivo As String)
        log("Rutina:ftp")

        Dim name As String
        statusFTP = "No Exportado"
        If archivo.Contains(".xml") Then
            Try
                Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(URI & archivo), System.Net.FtpWebRequest)
                clsRequest.Credentials = New System.Net.NetworkCredential(UserFTP, PassFTP)
                clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
                clsRequest.KeepAlive = False
                clsRequest.UseBinary = True
                clsRequest.UsePassive = False

                clsRequest.Proxy = Nothing


                clsRequest.ReadWriteTimeout = FTPTimeOut
                clsRequest.Timeout = FTPTimeOut
                Dim bFile() As Byte = System.IO.File.ReadAllBytes(dirExport & archivo)
                Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
                clsStream.Write(bFile, 0, bFile.Length)
                clsStream.Close()
                clsStream.Dispose()
                statusFTP = "Exportado"
            Catch ex As Exception
                log(ex.Message)
                log("Error FTP")
                statusFTP = "No Exportado"
            End Try

        ElseIf archivo.Contains(".wav") Then
            For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirExport, FileIO.SearchOption.SearchAllSubDirectories, archivo)
                Try
                    name = foundFile.Replace(dirExport, "")
                    Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(URI & name), System.Net.FtpWebRequest)
                    clsRequest.Credentials = New System.Net.NetworkCredential(UserFTP, PassFTP)
                    clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
                    clsRequest.KeepAlive = False
                    clsRequest.UsePassive = False
                    clsRequest.UseBinary = True

                   clsRequest.Proxy = Nothing

                    clsRequest.ReadWriteTimeout = FTPTimeOut
                    clsRequest.Timeout = FTPTimeOut
                    Dim bFile() As Byte = System.IO.File.ReadAllBytes(foundFile)
                    Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
                    clsStream.Write(bFile, 0, bFile.Length)
                    clsStream.Close()
                    clsStream.Dispose()
                    statusFTP = "Exportado"
                Catch ex As Exception
                    log(ex.Message)
                    log("Error FTP")
                    statusFTP = "No Exportado"
                End Try
            Next
        End If

    End Sub

    Sub Borrar(ByVal arch As String)
        log("Rutina:Borrar")


        For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirExport, FileIO.SearchOption.SearchTopLevelOnly, arch)
            Try
                My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                log("Archivo " & foundFile & " borrado")
            Catch ex As Exception
                log(ex.Message)
            End Try
        Next


    End Sub



    Sub DS()
        log("Rutina:DS")

        Try
            Dim objProcess As System.Diagnostics.Process = New System.Diagnostics.Process()
            objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            If DSource = 1 And Rext <> "" Then
                objProcess.StartInfo.FileName = Rext
                objProcess.Start()
                objProcess.WaitForExit()
                objProcess.Close()
                objProcess = Nothing

            ElseIf DSource = 2 Then
                objProcess.StartInfo.FileName = dirInstall & "QfinitiDS1.exe" 'Exportacion para archivos con el nombre (Caso Chile)
                objProcess.Start()
                objProcess.WaitForExit()
                objProcess.Close()
                objProcess = Nothing

            ElseIf DSource = 3 Then
                objProcess.StartInfo.FileName = dirInstall & "QfinitiDS2.exe" 'Exportacion para archivos excel exportados desde QfinitiDesktop (Caso Banesco)
                objProcess.Start()
                objProcess.WaitForExit()
                objProcess.Close()
                objProcess = Nothing

            ElseIf DSource = 4 Then
                objProcess.StartInfo.FileName = dirInstall & "QfinitiDS3.exe" 'Exportacion para archivos excel exportados desde Altitude (Caso Brasil)
                objProcess.Start()
                objProcess.WaitForExit()
                objProcess.Close()
                objProcess = Nothing

            End If
        Catch ex As Exception
            log(ex.Message)
        End Try


    End Sub



    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

    Sub log(ByVal mensaje As String)
        Try
            Dim oSW As New StreamWriter(dirInstall & "AppQfinitiExport.log", True)
            oSW.WriteLine(FechayHora() & " " & mensaje)
            oSW.Flush()
            oSW.Close()
            oSW = Nothing
            releaseObject(oSW)

            Dim info As New FileInfo(dirInstall & "AppQfinitiExport.log")
            If info.Length > loglen Then
                info.Delete()
            End If
            info = Nothing
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub




    Function FechayHora() As String
        FechayHora = Now.Date.ToString.Remove(InStr(Now.Date.ToString, " ")) & Now.TimeOfDay.ToString
    End Function

    Function ping() As Boolean

        ping = True


    End Function

    Function XMLwrite(ByVal nombreWav As String) As Boolean
        log("Funcion:XMLWrite")
        

        Try
            Dim xmlTransform As New Xsl.XslCompiledTransform
            xmlTransform.Load(dirInstall & "TemplateXML_FTP.xslt")
            Dim xmlFile As New XmlTextWriter(dirExport & nombreWav.Replace(".wav", ".xml"), System.Text.Encoding.UTF8)
            xmlFile.QuoteChar = Chr(34)
            xmlTransform.Transform(xmlDSNodo, xmlFile)
            xmlFile.Close()

            XMLwrite = True
            log("Creando archivo XML: " & nombreWav.Replace(".wav", ".xml"))

        Catch ex As Exception
            XMLwrite = False
            log("Error en la rutina XMLWrite")
            log(ex.Message)
        End Try

    End Function

    Public Function Verificar(ByVal trID As String) As String
        log("Funcion:Verificar")


        Dim w As Boolean = False
        Dim v As Boolean = False
        Dim x, y, z, t As String
        Dim document As XmlDocument = New XmlDocument()
        Dim navigator As XPath.XPathNavigator = document.CreateNavigator()
        Dim nav As XPath.XPathNavigator
        Dim manager As XmlNamespaceManager = New XmlNamespaceManager(navigator.NameTable)

        Try
            document.Load(dirInstall & "dbcontrol.xml")
            manager.AddNamespace("lg", "http://www.anew.com.ve/qfiniti")
            For Each nav In navigator.Select("/lg:Events/transaction[@trans_id = '" & trID & "']", manager)
                w = True
            Next

            If w = True Then
                x = navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & trID & "']/@status_file", manager).Value
                If x = "Existe" Then
                    y = navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & trID & "']/@status_ftp", manager).Value
                    If y = "No Exportado" Then
                        Verificar = "2"
                    Else
                        Verificar = "3"
                        v = True
                    End If
                Else
                    Verificar = "1"
                End If
            Else
                Verificar = "0"
            End If


            If v = True Then
                t = navigator.SelectSingleNode("/lg:Events/transaction[@trans_id = '" & trID & "']/@name_file", manager).Value
                t = t.Replace(".wav", ".xml")
                z = navigator.SelectSingleNode("/lg:Events/transaction[@name_file = '" & t & "']/@status_ftp", manager).Value
                If z = "No Exportado" Then
                    xportDataFile = True
                    Verificar = t
                End If
            End If

        Catch ex As Exception
            Verificar = "Error"
            xportDataFile = False
            log(ex.Message)
        End Try

    End Function


End Module


